package com.sun.TrapDoor;

import java.util.Random;

import com.Sun.Model.encryptedIndex;
import com.Sun.index.indexBuildTool;
import com.Sun.index.indexEncrypted;

import Jama.Matrix;

public class EncryptedTroopHelper {
	/**
	 * 将小数x分割为result[1]和result[2],使得result[1]+result[2]=x
	 * @param x
	 * @return
	 */
	public static double[]  SpiltDouble(double x)
	{
		double[] result=new double[2];
		Random random=new Random();
		if(x!=0)
		{
			result[0]=random.nextInt((int)x);
			result[1]=x-result[0];
		}
		else {
			result[0]=result[1]=0;
		}
		
		return result;
	}

	/**
	 * trapdoorPlain进行加密
	 * @param SK
	 * @param trapdoorPlain
	 * @return
	 */
	public static encryptedIndex encrypTropDoor(indexEncrypted SK,double []trapdoorPlain)
	{
		long startTime1=System.currentTimeMillis();
		encryptedIndex res=new encryptedIndex();
		int []S=SK.getS();
		Matrix M1=SK.getM1();
		Matrix M2=SK.getM2();
		double []tempMD1=new double[trapdoorPlain.length];
		double []tempMD2=new double[trapdoorPlain.length];
		for(int i=0;i<S.length;i++)
		{
			//如果S[i]==1,那么tempMD1[i]=tempMD2[i]=plainIndex[i]
			if(S[i]==1)
			{
				tempMD1[i]=tempMD2[i]=trapdoorPlain[i];
			}
			//如果S[i]==0,那么tempMD1[i]+tempMD2[i]=plainIndex[i]
			else {
				double []sp=indexBuildTool.splitDouble(trapdoorPlain[i]);
				tempMD1[i]=sp[0];
				tempMD2[i]=sp[1];
			}
		}
		long startTime=System.currentTimeMillis();
		Matrix M11=M1.inverse();
		Matrix M22=M2.inverse();
		long endTime=System.currentTimeMillis();
		System.out.println("生成可逆矩阵的时间是："+(endTime-startTime));
		Matrix encryMatrix1=M11.times(new Matrix(tempMD1,1).transpose());
		Matrix encryMatrix2=M22.times(new Matrix(tempMD2,1).transpose());
		tempMD1=indexBuildTool.getArrayFromMatrix(encryMatrix1);
		tempMD2=indexBuildTool.getArrayFromMatrix(encryMatrix2);
		res.setMD1(tempMD1);
		res.setMD2(tempMD2);
		long endTIme1=System.currentTimeMillis();
		System.out.println("加密明文搜索索引的时间是："+((endTIme1-startTime1)-(endTime-startTime)));
		return res;
		
	}

}
